package dbops

import (
	"fmt"
	"gitee.com/DengAnbang/Wefore/src/bean"
	"gitee.com/DengAnbang/Wefore/src/code"
	"gitee.com/DengAnbang/Wefore/src/push"
	"gitee.com/DengAnbang/goutils/dbutils"
	"gitee.com/DengAnbang/goutils/utils"
	"os"
	"path/filepath"
	"strconv"
	"time"
)

type ChatMessage struct {
	MessageId   int64    `json:"message_id"`
	ToUser      BaseUser `json:"to_user"`
	FormUser    BaseUser `json:"form_user"`
	Content     string   `json:"content"`
	IsRead      int      `json:"is_read"`
	FileId      string   `json:"file_id"`
	MessageType string   `json:"message_type"`
	Created     string   `json:"created"`
}

func NewChatMessage(data map[string]string) ChatMessage {
	messageId, err := strconv.ParseInt(data["message_id"], 10, 64)
	if err != nil {
		messageId = 0
	}
	return ChatMessage{
		MessageId: messageId,
		ToUser: BaseUser{
			UserName:     data["to_user_name"],
			UserId:       data["to_user_id"],
			HeadPortrait: data["to_user_head_portrait"],
		},
		FormUser: BaseUser{
			UserName:     data["form_user_name"],
			UserId:       data["form_user_id"],
			HeadPortrait: data["form_user_head_portrait"],
		},
		Content:     data["content"],
		IsRead:      utils.String2int(data["is_read"], 0),
		FileId:      data["file_id"],
		MessageType: data["message_type"],
		Created:     data["message_created"],
	}
}
func ChatMessageSend(formUserId, toUserId, content, fileId, messageType string) error {
	if len(formUserId) == 0 {
		return bean.NewErrorMessage("发送人ID不能为空")
	}
	if len(toUserId) == 0 {
		return bean.NewErrorMessage("接收人ID不能为空")
	}
	if len(content) == 0 {
		return bean.NewErrorMessage("发送人ID不能为空")
	}
	if len(formUserId) == 0 {
		return bean.NewErrorMessage("发送人ID不能为空")
	}
	stmtIn, err := dbConn.Prepare("INSERT INTO table_chat (form_user_id,to_user_id,content,file_id,message_type)VALUES(?,?,?,?,?)")
	if err != nil {
		return err
	}
	in, err := stmtIn.Exec(formUserId, toUserId, content, fileId, messageType)
	if err != nil {
		return err
	}
	messageId, err := in.LastInsertId()
	if err != nil {
		return err
	}
	_ = stmtIn.Close()
	formBean, err := UserSelectByUserId(formUserId)
	if err != nil {
		return err
	}
	toBean, err := UserSelectByUserId(toUserId)
	if err != nil {
		return err
	}

	message := ChatMessage{
		MessageId:   messageId,
		ToUser:      toBean.BaseUser,
		FormUser:    formBean.BaseUser,
		Content:     content,
		FileId:      fileId,
		MessageType: messageType,
		Created:     fmt.Sprint(time.Now().Unix()),
	}
	//推送
	push.Push(toUserId, code.TypePushChat, message)
	return nil
}

func ChatMessageDelete(messageIds string, fileId string) error {
	messageId := utils.String2int(messageIds, -1)
	if messageId == 0 {
		return bean.NewErrorMessage("ID不能为空")
	}
	stmtIn, err := dbConn.Prepare("DELETE FROM table_chat WHERE id=?")
	if err != nil {
		return err
	}
	_, err = stmtIn.Exec(messageId)
	if err != nil {
		return err
	}
	_ = stmtIn.Close()
	FileRoot := code.FileRootPath + "/" + "chat" + "/" + fileId + "/"
	clean := filepath.Clean(FileRoot)
	err = os.RemoveAll(clean)
	return nil
}

func ChatMessageSelectToMe(toUserId string) ([]ChatMessage, error) {
	var chatMessages = make([]ChatMessage, 0)
	if len(toUserId) == 0 {
		return chatMessages, bean.NewErrorMessage("用户Id不能为空")
	}
	stmtOut, err := dbConn.Prepare(`SELECT * ,
table_chat.created as message_created,
table_chat.id as message_id,
tu1.name as to_user_name,
tu1.user_id as to_user_id,
tu1.head_portrait as to_user_head_portrait,
tu2.name as form_user_name,
tu2.head_portrait as form_user_head_portrait,
tu2.user_id as form_user_id
FROM table_chat 
LEFT OUTER JOIN table_user tu1 on table_chat.to_user_id = tu1.user_id
LEFT OUTER JOIN table_user tu2 on table_chat.form_user_id = tu2.user_id
where to_user_id=?`)
	if err != nil {
		return chatMessages, err
	}
	rows, err := stmtOut.Query(toUserId)
	if err != nil {
		return chatMessages, err
	}

	for rows.Next() {
		mapStrings, err := dbutils.GetRowsMap(rows)
		for err != nil {
			return chatMessages, err
		}
		attendance := NewChatMessage(mapStrings)
		chatMessages = append(chatMessages, attendance)
	}
	return chatMessages, nil
}
